import { ShelfCourse } from '@/api/Shelf';
import { CoursewaresList } from '@/components/CoursewaresList';
import { SourceSelectModal } from '@/components/SourceSelect';
import Source from '@/components/SourceSelect/Entity/Source';
import { useRequest } from 'ahooks';
import type { DatePickerProps, UploadFile } from 'antd';
import { Button, Card, Checkbox, DatePicker, Form, Input, message, Space } from 'antd';
import dayjs from 'dayjs';
import { useCallback, useMemo, useState } from 'react';
import { useYmAliOss, YmAddPageLayout, YmUpload, type YmAddPageLayoutProps } from 'ym-design';

export interface AddEditPorps {
  courseId?: string;
  faceImg?: string;
  onBack?(): void;
  courseName?: string;
  learnEndTime?: string;
  learnStartTime?: string;
}

type FormValue = {
  courseId?: string;
  coursewares?: Source[];
  courseName?: string;
  faceImg?: UploadFile[];
  timerRange: [dayjs.Dayjs, dayjs.Dayjs];
};
const { PaneItem } = YmAddPageLayout;
export function AddEdit({ onBack, courseId, courseName, faceImg, learnEndTime, learnStartTime }: AddEditPorps) {
  //   const [itemProps] = CategoryCascader.useFieldLevelTwo(classId && parClassId ? [parClassId, classId] : undefined);
  const [form] = Form.useForm<FormValue>();
  const [modalOpen, setModalOpen] = useState<number>();
  const [minStartTime] = useState<dayjs.Dayjs>(() => {
    return dayjs().add(15, 'minutes');
  });
  const [maxEndTime] = useState<dayjs.Dayjs>(() => {
    return dayjs('2099-12-01 00:00:00');
  });

  const [isLong, setIsLong] = useState(() => {
    return maxEndTime.format('YYYY-MM-DD HH:mm:ss') === learnEndTime;
  });

  const [initValue] = useState<FormValue>(() => {
    return {
      timerRange: [
        learnStartTime ? dayjs(learnStartTime) : minStartTime,
        learnEndTime ? dayjs(learnEndTime) : minStartTime.clone().add(1, 'day').add(15, 'minutes'),
      ],
      faceImg: faceImg ? [{ url: faceImg, uid: faceImg, name: faceImg }] : [],
      courseName,
    };
  });

  useRequest(
    async () => {
      if (courseId) {
        return Source.listWithRelationType('course', courseId);
      }
    },
    {
      ready: Boolean(courseId),
      onSuccess(data) {
        form.setFieldsValue({ coursewares: data });
      },
    },
  );

  const { run, loading } = useRequest(ShelfCourse.createOrUpdate, {
    manual: true,
    onSuccess() {
      onBack?.();
    },
  });

  const customRequest = useYmAliOss();

  // 如果是23点55分之后，则只能选择次日。否则可以选择当天
  const disabledDate = useCallback<NonNullable<DatePickerProps['disabledDate']>>(
    (current) => {
      if (current.isAfter(minStartTime) || minStartTime.format('YYYYMMDD') === current.format('YYYYMMDD')) {
        return false;
      } else {
        return true;
      }
    },
    [minStartTime],
  );

  // 不可点击的时分
  const disabledDateTime = useCallback(
    (dates: dayjs.Dayjs | null) => {
      const range = (start: number, end: number) => {
        const result = [];
        for (let i = start; i < end; i++) {
          result.push(i);
        }
        return result;
      };

      if (dates && dates.format('YYYYMMDD') === minStartTime.format('YYYYMMDD')) {
        // 需要限制
        console.log('需要限制走到了么', '-----');
        return {
          disabledHours() {
            const hour = minStartTime.hour();
            console.log(hour, range(hour, 23));
            return range(0, hour);
          },
          disabledMinutes(hour: number) {
            if (hour === minStartTime.hour()) {
              return range(0, minStartTime.minute());
            } else {
              return [];
            }
          },
        };
      } else {
        // 不需要限制
        return {};
      }
    },
    [minStartTime],
  );

  // 保存
  const sub = async () => {
    const { coursewares: _coursewares = [], timerRange, faceImg: _faceImg, ...value } = await form.validateFields();
    const params = {
      courseId,
      coursewares: _coursewares.map((v) => {
        return {
          coursewareId: v.id,
        };
      }),
      learnEndTime: isLong ? maxEndTime.valueOf() : timerRange[1].valueOf(),
      learnStartTime: timerRange[0].valueOf(),
      faceImg: _faceImg?.map((v) => v.response || v.url).join(','),
      ...value,
    };
    if (params.coursewares.length === 0) {
      message.error('请选择学习内容');
      return;
    }
    console.log(params);
    run(params);
  };

  const operationFooter = useMemo(() => {
    const operationBtn = [
      <Button key="subOncsavee" type="primary" size="small" disabled={loading} onClick={sub}>
        保存
      </Button>,
    ];
    return operationBtn;
  }, [loading]);

  const layoutParams: YmAddPageLayoutProps = useMemo(
    () => ({
      leftOperation: {
        onBack: () => {
          onBack?.();
        },
      },
      rightOperationDom: operationFooter,
      destroyInactiveTabPane: false,
    }),
    [operationFooter],
  );
  return (
    <YmAddPageLayout {...layoutParams}>
      <PaneItem tabKey="tab1" label={courseId ? '编辑课程' : '创建课程'} className="pane_tab1">
        <div style={{ height: '100%', overflow: 'auto' }}>
          <Form form={form} labelCol={{ style: { width: 100 } }} initialValues={initValue}>
            <Card title="基础信息" style={{ marginBottom: 16 }}>
              <Form.Item label="课程名称" name="courseName" rules={[{ required: true }]}>
                <Input showCount maxLength={18}></Input>
              </Form.Item>
              <Form.Item label="学习时间">
                <div style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
                  <Form.Item
                    name={['timerRange', 0]}
                    hidden={!isLong}
                    noStyle
                    getValueFromEvent={(date: dayjs.Dayjs) => {
                      if (date.isAfter(minStartTime)) return date;
                      else return minStartTime;
                    }}
                  >
                    <DatePicker
                      allowClear={false}
                      showTime={{ format: 'YYYY-MM-DD HH:mm' }}
                      format="YYYY-MM-DD HH:mm"
                      disabledDate={disabledDate}
                      disabledTime={disabledDateTime}
                      showNow={false}
                    />
                  </Form.Item>
                  <Form.Item
                    name="timerRange"
                    noStyle
                    hidden={isLong}
                    rules={[
                      {
                        async validator(rulse, value: dayjs.Dayjs[]) {
                          if (value && value[0].isBefore(dayjs())) {
                            return Promise.reject('开始时间必须大于当前时间');
                          }
                        },
                      },
                    ]}
                  >
                    <DatePicker.RangePicker
                      allowClear={false}
                      showTime={{ format: 'YYYY-MM-DD HH:mm' }}
                      format="YYYY-MM-DD HH:mm"
                      disabledDate={disabledDate}
                      disabledTime={disabledDateTime}
                      showNow={false}
                    />
                  </Form.Item>
                  <Checkbox
                    checked={isLong}
                    onChange={(e) => {
                      setIsLong(e.target.checked);
                    }}
                  >
                    长期
                  </Checkbox>
                </div>
              </Form.Item>
              <Form.Item label="封面图">
                <Space size={20}>
                  <Form.Item name="faceImg" noStyle rules={YmUpload.formRules(false)}>
                    <YmUpload maxCount={1} cardWidth={375} cardHeight={200} customRequest={customRequest}>
                      请上传封面
                    </YmUpload>
                  </Form.Item>
                  <div>
                    <p>图片仅支持jpg、png格式 </p>
                    <p> 图片大小750*400 </p>
                  </div>
                </Space>
              </Form.Item>
            </Card>
            <Card
              title="选择课件"
              extra={
                <Button
                  type="primary"
                  shape="round"
                  onClick={() => {
                    setModalOpen(Math.random());
                  }}
                >
                  选择
                </Button>
              }
            >
              <Form.Item name="coursewares" noStyle>
                <SourceSelectModal openDep={modalOpen} preSet="课件"></SourceSelectModal>
              </Form.Item>
              <Form.Item name="coursewares" noStyle>
                <CoursewaresList />
              </Form.Item>
            </Card>
          </Form>
        </div>
      </PaneItem>
    </YmAddPageLayout>
  );
}
